package com.cheyunkeji.er.fragment.evaluate;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.activity.evaluate.EngineCabinCheckBCSMActivity;
import com.cheyunkeji.er.activity.evaluate.EvaluateWorkflowActivity;
import com.cheyunkeji.er.activity.evaluate.PhotoPreViewActivity;
import com.cheyunkeji.er.base.BaseFragment;
import com.cheyunkeji.er.bean.evaluate.EvaluateDetailResult2;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.service.OssService;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.evaluate.EvaluateCheckItemView2;
import com.cheyunkeji.er.view.evaluate.ImageSelectDialog;
import com.google.gson.Gson;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.utils.ImageCaptureManager;
import okhttp3.Call;
import okhttp3.Request;

import static android.app.Activity.RESULT_OK;

/**
 * Created by Michael on 2017/4/12 13:45.
 */

public class EngineCabinCheckFragment extends BaseFragment implements CompoundButton.OnCheckedChangeListener, EvaluateCheckItemView2.OnPhotoIconClicked, EvaluateWorkflowActivity.OnOutActionListener, OssService.onImageProcessedResultListener, ImageSelectDialog.ImageSelectListener {


    public static final int PAGE_INDEX = 8;
    private static final String TAG = EngineCabinCheckFragment.class.getSimpleName();
    private static final int PREVIEW_IMG_REQUEST = 0xff10;
    private static int uploadImgCounter = 0;

    @BindView(R.id.cb_all_check_ok)
    CheckBox cbAllCheckOk;
    @BindView(R.id.check_item_1)
    EvaluateCheckItemView2 checkItem1;
    @BindView(R.id.check_item_2)
    EvaluateCheckItemView2 checkItem2;
    @BindView(R.id.check_item_3)
    EvaluateCheckItemView2 checkItem3;
    @BindView(R.id.check_item_4)
    EvaluateCheckItemView2 checkItem4;
    @BindView(R.id.check_item_5)
    EvaluateCheckItemView2 checkItem5;
    @BindView(R.id.check_item_6)
    EvaluateCheckItemView2 checkItem6;
    @BindView(R.id.check_item_7)
    EvaluateCheckItemView2 checkItem7;
    @BindView(R.id.check_item_8)
    EvaluateCheckItemView2 checkItem8;
    @BindView(R.id.check_item_9)
    EvaluateCheckItemView2 checkItem9;
    @BindView(R.id.check_item_10)
    EvaluateCheckItemView2 checkItem10;
    @BindView(R.id.rl_bcsm)
    RelativeLayout rlBcsm;
    @BindView(R.id.tv_previous_step)
    TextView tvPreviousStep;
    @BindView(R.id.tv_next_step)
    TextView tvNextStep;
    @BindView(R.id.ll_content)
    LinearLayout llContent;
    @BindView(R.id.iv_goto_top)
    ImageView ivGotoTop;
    @BindView(R.id.sc_content)
    ScrollView scContent;
    private ArrayList<EvaluateCheckItemView2> checkItems;
    private List<EvaluateDetailResult2.DetectionBean.EncompBean> encompList;

    private ImageSelectDialog imgSelectDialog;
    private ImageCaptureManager captureManager;
    private Runnable mTask;

    @Override
    protected void doInflaterView(LayoutInflater inflater, ViewGroup container) {
        contentView = inflater.inflate(R.layout.er_frag_engine_cabin_check, container, false);
        ButterKnife.bind(this, contentView);
    }

    @Override
    protected void init() {
        checkItems = new ArrayList<>(10);
        checkItems.add(checkItem1);
        checkItems.add(checkItem2);
        checkItems.add(checkItem3);
        checkItems.add(checkItem4);
        checkItems.add(checkItem5);
        checkItems.add(checkItem6);
        checkItems.add(checkItem7);
        checkItems.add(checkItem8);
        checkItems.add(checkItem9);
        checkItems.add(checkItem10);

        captureManager = new ImageCaptureManager(getActivity());
    }

    @Override
    protected void initView() {
        ivGotoTop.setOnClickListener(this);
        rlBcsm.setOnClickListener(this);
        tvPreviousStep.setOnClickListener(this);
        tvNextStep.setOnClickListener(this);

//      设置照相机图标点击事件回调
        for (EvaluateCheckItemView2 checkItem : checkItems) {
            checkItem.setOnPhotoIconClickedListener(this);
        }

        cbAllCheckOk.setOnCheckedChangeListener(this);
    }

    @Override
    protected void initData() {
    }

    @Override
    public void onResume() {
        super.onResume();
        displayInfo();
    }

    private void displayInfo() {
        if (null != MyApplication.getInstance().getEvaluateResult() && null != MyApplication.getInstance().getEvaluateResult().getDetection() && null != MyApplication.getInstance().getEvaluateResult().getDetection().getEncomp()) {
            encompList = MyApplication.getInstance().getEvaluateResult().getDetection().getEncomp();
            if(encompList==null || encompList.size() == 0){
                //默认全选
                cbAllCheckOk.setChecked(true);
            }else{
                for (int i = 0; i < encompList.size(); i++) {
                    checkItems.get(encompList.get(i).getId() - 1).setTag(encompList.get(i));
                    checkItems.get(encompList.get(i).getId() - 1).setCheckedIndex(encompList.get(i).getStatus());
                    checkItems.get(encompList.get(i).getId() - 1).setPhotoBtnState(!TextUtils.isEmpty(encompList.get(i).getImage()));
                    checkItems.get(encompList.get(i).getId() - 1).setRemarksDesc(encompList.get(i).getMark());
                }
            }
        }else{
            //默认全选
            cbAllCheckOk.setChecked(true);
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_goto_top:
                scContent.smoothScrollTo(0, 0);
                break;
            case R.id.rl_bcsm:
                startActivity(new Intent(getActivity(), EngineCabinCheckBCSMActivity.class));
                break;
            case R.id.tv_next_step:
                onSaveEvaluateResult(new Runnable() {
                    @Override
                    public void run() {
                        goToNextPage();
                    }
                });
                break;
            case R.id.tv_previous_step:
                onSaveEvaluateResult(new Runnable() {
                    @Override
                    public void run() {
                        goToPreviousPage();
                    }
                });
                break;
            default:
                break;
        }
    }

    /**
     * 进入图片选择页面
     */
    private void pickPhoto() {
        PhotoPicker.builder()
                .setPhotoCount(1)
                .start(getActivity(), this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case PhotoPicker.REQUEST_CODE:
                if (data != null && null != data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS).get(0)) {
                    String localImgPath = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS).get(0);
                    Log.e(TAG, "onActivityResult: " + localImgPath + " EvaluateCheckItem : " + llContent.getTag());
                    EvaluateCheckItemView2 checkItem = checkItems.get((int) llContent.getTag() - 1);
                    checkItem.setImgPath(localImgPath);
                    if (null == checkItem.getTag()) {
                        checkItem.setTag(new EvaluateDetailResult2.DetectionBean.EncompBean((int) llContent.getTag(), checkItem.getCheckedIndex(), checkItem.getRemarkDesc(), localImgPath));
                    } else {
                        ((EvaluateDetailResult2.DetectionBean.EncompBean) checkItem.getTag()).setImage(localImgPath);
                    }
                    checkItem.setPhotoBtnState(true);
                }
                break;

            case PREVIEW_IMG_REQUEST:
                if (data == null) {
                    return;
                }

                boolean deleteImg = data.getBooleanExtra("DELETE_IMG", false);
                Log.e(TAG, "onActivityResult: " + deleteImg);

                if (deleteImg) {
                    checkItems.get((int) llContent.getTag() - 1).setImgPath("");
                    checkItems.get((int) llContent.getTag() - 1).setCheckedIndex(4);
                    ((EvaluateDetailResult2.DetectionBean.EncompBean) checkItems.get((int) llContent.getTag() - 1).getTag()).setImage("");
                    checkItems.get((int) llContent.getTag() - 1).setPhotoBtnState(false);
                }
                break;

            case ImageCaptureManager.REQUEST_TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    captureManager.galleryAddPic();
                    String path = captureManager.getCurrentPhotoPath();
                    EvaluateCheckItemView2 checkItem = checkItems.get((int) llContent.getTag() - 1);
                    checkItem.setImgPath(path);
                    if (null == checkItem.getTag()) {
                        checkItem.setTag(new EvaluateDetailResult2.DetectionBean.EncompBean((int) llContent.getTag(), checkItem.getCheckedIndex(), checkItem.getRemarkDesc(), path));
                    } else {
                        ((EvaluateDetailResult2.DetectionBean.EncompBean) checkItem.getTag()).setImage(path);
                    }
                    checkItem.setPhotoBtnState(true);
                }
                break;

            default:
                break;

        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            for (EvaluateCheckItemView2 checkItem : checkItems) {
                if (checkItem.getCheckedIndex() != 0) {
                    checkItem.setCheckedIndex(0);
                }
            }
        } else {
//                如果是手动选中，则全部反选
            for (EvaluateCheckItemView2 checkItem : checkItems) {
                if (checkItem.getCheckedIndex() != 4) {
                    checkItem.setCheckedIndex(4);
                }
            }
        }

    }

    @Override
    public void takePhoto(int evaluateItemIndex) {
        llContent.setTag(evaluateItemIndex);
        if (null != checkItems.get(evaluateItemIndex - 1).getTag() && !TextUtils.isEmpty(((EvaluateDetailResult2.DetectionBean.EncompBean) checkItems.get(evaluateItemIndex - 1).getTag()).getImage())) {
//          有照片，预览照片
            Intent intent = new Intent(getActivity(), PhotoPreViewActivity.class);
            intent.putExtra("IMG_PATH", ((EvaluateDetailResult2.DetectionBean.EncompBean) checkItems.get(evaluateItemIndex - 1).getTag()).getImage());
            this.startActivityForResult(intent, PREVIEW_IMG_REQUEST);
        } else {
//       选择照片
//            pickPhoto();
            showImgSelectDialog("");
        }
    }

    public void showImgSelectDialog(String titleStr) {
        if (null == imgSelectDialog) {
            imgSelectDialog = new ImageSelectDialog(this.getActivity(), this, titleStr);
        } else {
            imgSelectDialog.setTitleStr(titleStr);
        }
        imgSelectDialog.show();
    }

    @Override
    public void onItemChecked(int cbIndex, int evaluateItemIndex) {
        EvaluateCheckItemView2 checkItem = checkItems.get(evaluateItemIndex - 1);
        if (null == checkItems.get(evaluateItemIndex - 1).getTag()) {
            checkItem.setTag(new EvaluateDetailResult2.DetectionBean.EncompBean(evaluateItemIndex, cbIndex, checkItem.getRemarkDesc(), checkItem.getImgPath()));
        } else {
            ((EvaluateDetailResult2.DetectionBean.EncompBean) checkItem.getTag()).setStatus(cbIndex);
        }
    }

    @Override
    public void onSaveEvaluateResult(Runnable task) {
        if (task != null) {
            mTask = task;
        }
//       只要有选择照片，就去上传
        for (int i = 0; i < checkItems.size(); i++) {
            if (null != checkItems.get(i).getTag() && ((EvaluateDetailResult2.DetectionBean.EncompBean) checkItems.get(i).getTag()).getStatus() != 4 &&
                    !TextUtils.isEmpty(((EvaluateDetailResult2.DetectionBean.EncompBean) checkItems.get(i).getTag()).getImage()) &&
                    !((EvaluateDetailResult2.DetectionBean.EncompBean) checkItems.get(i).getTag()).getImage().startsWith("http")) {

                uploadImage();
                return;
            }
        }
//      如果没有选择照片，则不需上传，直接保存结果
        saveData();
    }

    private void uploadImage() {
        Gson gson = new Gson();
        for (int i = 0; i < checkItems.size(); i++) {
            if (null != checkItems.get(i).getTag() && ((EvaluateDetailResult2.DetectionBean.EncompBean) checkItems.get(i).getTag()).getStatus() != 4 &&
                    !TextUtils.isEmpty(((EvaluateDetailResult2.DetectionBean.EncompBean) checkItems.get(i).getTag()).getImage())) {
                Log.e(TAG, "onSaveEvaluateResult: 带上传图片" + gson.toJson(checkItems.get(i).getTag()));
                if (!((EvaluateDetailResult2.DetectionBean.EncompBean) checkItems.get(i).getTag()).getImage().startsWith("http")) {
                    // 上传图片
                    MyApplication.getInstance().getOssService(this).asyncPutImage(OssService.getOssObjectInfo(true),
                            ((EvaluateDetailResult2.DetectionBean.EncompBean) checkItems.get(i).getTag()).getImage(),
                            String.valueOf(((EvaluateDetailResult2.DetectionBean.EncompBean) checkItems.get(i).getTag()).getId()));
                    ++uploadImgCounter;
                    Log.e(TAG, "onSaveEvaluateResult: " + uploadImgCounter);
                    showDialog();
                }
            }
        }
    }


    @Override
    public void onUploadOk(String imgUrl, Object tag) {
        Log.e(TAG, "onUploadOk: 上传成功 ： " + imgUrl);
        ((EvaluateDetailResult2.DetectionBean.EncompBean) checkItems.get(Integer.valueOf((String) tag) - 1).getTag()).setImage(imgUrl);
        --uploadImgCounter;
        if (uploadImgCounter == 0) {
            saveData();
        }
    }

    private void saveData() {
        List<EvaluateDetailResult2.DetectionBean.EncompBean> tempList = new ArrayList<>();
        for (int i = 0; i < checkItems.size(); i++) {
            if (null != checkItems.get(i).getTag() && ((EvaluateDetailResult2.DetectionBean.EncompBean) checkItems.get(i).getTag()).getStatus() != 4) {
                ((EvaluateDetailResult2.DetectionBean.EncompBean) checkItems.get(i).getTag()).setMark(checkItems.get(i).getRemarkDesc());
                tempList.add(((EvaluateDetailResult2.DetectionBean.EncompBean) checkItems.get(i).getTag()));
            }
        }
        String jsonStr = new StringBuilder("{\"encomp\":").append(new Gson().toJson(tempList)).append("}").toString();
        Log.e(TAG, "saveData: 最后结果 ：  " + jsonStr);
        HashMap<String, String> params = new HashMap<>();
        //      params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
        params.put("aid", MyApplication.getInstance().getEvaluateResult().getAid());
        params.put("detection", jsonStr);

        if (MyApplication.getInstance().getEvaluateResult() == null || MyApplication.getInstance().getEvaluateResult().getIroute() == null || MyApplication.getInstance().getEvaluateResult().getIroute().size() == 0) {
            int[] iroute = new int[15];
            iroute[PAGE_INDEX] = 1;
            String json = new Gson().toJson(iroute);
            Log.e(TAG, "saveData: 评估记录为空或数组为空时 保存记录数组 ：  " + json.substring(1, json.length() - 1));
            params.put("iroute", json.substring(1, json.length() - 1));
        } else {
            MyApplication.getInstance().getEvaluateResult().getIroute().set(PAGE_INDEX, 1);
            String json = new Gson().toJson(MyApplication.getInstance().getEvaluateResult().getIroute());
            params.put("iroute", json.substring(1, json.length() - 1));
            Log.e(TAG, "saveData:  保存记录数组 ：记录非空并且数组非空时 保存记录数组 ：   " + json.substring(1, json.length() - 1));
        }

        Log.e(TAG, "saveData: 发送请求 :  " + MyApplication.getInstance().getEvaluateResult().getAid());

        //        根据评估类型进行保存或编辑
        int evaluateType = ((EvaluateWorkflowActivity) getActivity()).getEvaluateArchiveType();
//       保存新创建、未上传待评估数据
        if (evaluateType == Constants.ARCHIVE_TYPE_CREATE_NEW_EVALUATE || evaluateType == Constants.ARCHIVE_TYPE_UN_UPLOAD_TO_EVALUATE || evaluateType == Constants.ARCHIVE_TYPE_WITH_FAST_EVALUATE_VIN) {
            ApiClient.postForm(((EvaluateWorkflowActivity) getActivity()).getCURRENT_TO_UPLOAD_RESULT_URL(), params, new RespCallback<EvaluateDetailResult2>() {

                        @Override
                        protected void onRequestFailed(String msg) {
                            SToast.show(msg);
                            if (mTask instanceof EvaluateWorkflowActivity.ExitRunnable) {
                                mTask.run();
                                mTask = null;
                            }
                        }

                        @Override
                        protected void onSuccess(EvaluateDetailResult2 data) {
                            if (null != data) {
                                MyApplication.getInstance().setEvaluateResult(data);
//                                SToast.show("保存成功");
                                Log.e(TAG, "onSuccess: " + "保存成功!");
                                displayInfo();
                                if (null != mTask) {
                                    mTask.run();
                                    mTask = null;
                                }
                            }
                        }

                        @Override
                        public void onBefore(Request request, int id) {
                            showDialog();
                        }

                        @Override
                        public void onAfter(int id) {
                            dismissDialog();
                        }
                    }
            );

        } else if (evaluateType == Constants.ARCHIVE_TYPE_UPLOADED_TO_EDIT) {
            ApiClient.postForm(((EvaluateWorkflowActivity) getActivity()).getCURRENT_TO_UPLOAD_RESULT_URL(), params, new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    // 网络异常
                    if (e instanceof UnknownHostException || e instanceof SocketException) {
                        SToast.show(R.string.tip_network_error, Gravity.CENTER);
                        return;
                    }
                }

                @Override
                public void onResponse(String response, int id) {
                    try {
                        JSONObject obj = new JSONObject(response);
                        if (obj.optInt("code") == 1) {
                            Log.e(TAG, "onResponse: 编辑成功 : " + obj.optString("data"));
                            if (null != mTask) {
                                mTask.run();
                                mTask = null;
                            }
                        } else {
                            SToast.show( obj.optString("msg") );
                            if (mTask instanceof EvaluateWorkflowActivity.ExitRunnable) {
                                mTask.run();
                                mTask = null;
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onBefore(Request request, int id) {
                    showDialog();
                }

                @Override
                public void onAfter(int id) {
                    dismissDialog();
                }
            });
        }


    }

    private void goToPreviousPage() {
        ((EvaluateWorkflowActivity) getActivity()).setCurrentPage(TyreCheckFragment.PAGE_INDEX);
    }

    private void goToNextPage() {
        ((EvaluateWorkflowActivity) getActivity()).setCurrentPage(DriveCabinCheckFragment.PAGE_INDEX);
    }

    @Override
    public void onUploadFailed() {
        SToast.show("图片上传失败！请重试");
    }

    private void openSystemCamera() {
        Intent intent = null;
        try {
            intent = captureManager.dispatchTakePictureIntent();
            startActivityForResult(intent, ImageCaptureManager.REQUEST_TAKE_PHOTO);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onTakePhotoWithSystemCamera() {
        openSystemCamera();
    }


    @Override
    public void onSelectImgOnGallery() {
        pickPhoto();
    }

}
